package 算法.练习1;

import 算法.NiuKe.TreeNode;

import java.util.ArrayList;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * @author:谢君臣
 * @Date:2021/8/16-10:27
 * @version:1.0
 * @function:
 */
public class NC8 {
    public static void main(String[] args) {

    }

    public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
        // write code here
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        findPath(res,root,sum,new ArrayList<>());
        return res;
    }
    private void findPath(ArrayList<ArrayList<Integer>> res,TreeNode root, int sum,ArrayList<Integer> path){
        if (root == null || (sum == 0 && leaf(root))) {
        }
        else {
            if (root.val==sum&&leaf(root))
            {
                path.add(root.val);
                res.add(path);
            } else{
                sum = sum - root.val;
                path.add(root.val);
                findPath(res, root.left, sum, new ArrayList<>(path));
                findPath(res, root.right, sum, new ArrayList<>(path));
            }
        }
    }

    private boolean leaf(TreeNode root) {
        if (root == null || root.left != null || root.right != null)
            return false;
        else return true;
    }
}
